#define  _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"


void QueueInit(Queue* pq)
{
	assert(pq);

	pq->tail = pq->head = NULL;
	pq->size = 0;
}

void QueueDestroy(Queue* pq)
{
	assert(pq);

	QueueNode* cur = pq->head;
	while (cur)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}
}

void QueuePush(Queue* pq, QueueDateType x)
{
	assert(pq);

	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}

	newnode->next = NULL;
	newnode->val = x;

	if (pq->head == NULL)
	{
		pq->tail = pq->head = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}

	pq->size++;
}

void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
		pq->size--;
	}
	else
	{
		QueueNode* next = pq->head->next;
		free(pq->head);

		pq->head = next;
		pq->size--;
	}
}

QueueDateType QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->head->val;
}

QueueDateType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->tail->val;
}

int QueueSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

bool QueueEmpty(Queue* pq)
{
	assert(pq);

	return pq->head == NULL;
}

void QueuePrint(Queue* pq)
{
	assert(pq);

	while (pq->head)
	{
		printf("%d ", pq->head->val);
		pq->head = pq->head->next;
	}
	printf("\n");
}
